package com.zjgk.hotel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zjgk.hotel.dao.mapper.UserMapper;
import com.zjgk.hotel.dao.pojo.User;
import com.zjgk.hotel.service.AdminService;
import com.zjgk.hotel.service.UserService;
import com.zjgk.hotel.utils.JWTUtils;
import com.zjgk.hotel.vo.Result;
import com.zjgk.hotel.vo.params.WxInfoParams;
import com.zjgk.hotel.vo.params.WxUserLoginParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserServiceImpl userService;

    @Transactional
    @Override
    public Result adminLogin(String username,String pwd) {
        try {
            int salt = userMapper.getSaltByUsername(username);
            String asHex = DigestUtils.md5DigestAsHex((pwd + salt).getBytes());

            User user = userMapper.adminLogin(username,asHex);
            if (user == null){
                return new Result(Result.NO_CORRESPONDING_DATA,"用户名或密码或权限错误");
            }

            String token = JWTUtils.createToken(user.getId());
            if (userService.holdNumber(user.getId(), token)){
                redisTemplate.opsForValue().set(token,JSONObject.toJSONString(user));
            }
            return new Result(Result.SUCCESS,"cg",token);
        }catch (Exception e){
            return new Result(Result.SERVER_ERROR,"服务器错误或网络错误",e.getMessage());
        }

    }
}
